package org.realogic.btp.sequence;

import java.util.UUID;

import org.realogic.btp.sequence.service.SequenceGenerateService;
import org.realogic.cfm.KAppContext;

public final class KSequenceGenerator {

	private SequenceGenerateService sequenceGenerateService;

	private KSequenceGenerator() {
		sequenceGenerateService = KAppContext.getBean("btp.sequenceGenerateService");
		if (sequenceGenerateService == null) {
			throw new IllegalStateException("btp.sequenceGenerateService is null");
		}
	}

	/**
	 * 根据流水号规则表，产生一个新的流水号
	 * 
	 * @param aVariableName
	 *            业务实体名称
	 * @return String
	 */
	public synchronized String generateSequence(String aVariableName) {
		return sequenceGenerateService.generateSequence(aVariableName);
	}

	/**
	 * 产生一个新的流水号
	 * 
	 * @param aVariableName
	 * @return
	 */
	public static String nextUniqueID(String aVariableName) {
		return LazyHolder.INSTANCE.generateSequence(aVariableName);
	}

	/**
	 * 获取long类型uuid
	 * 
	 * @return long
	 */
	public static long uuidOfLang() {
		return UUID.randomUUID().getMostSignificantBits();
	}

	/**
	 * 获取long类型uuid，值大于0
	 * 
	 * @return long
	 */
	public static long uuidOfAbsLongs() {
		while (true) {
			long r = uuidOfLang();
			if (r > 0L) {
				return r;
			}
		}
	}

	/**
	 * 获取36进制uuid
	 * 
	 * @param prex
	 *            前缀
	 * @param size
	 *            长度
	 * @return
	 */
	public static String uuidOf36String(String prex, int size) {
		long theValue = uuidOfAbsLongs();
		String tmp = Long.toString(theValue, 36).toUpperCase();
		String s = "";
		int len = tmp.length();
		int x = size - len;
		for (int i = 0; i < x; i++) {
			s = "0".concat(s);
		}
		if (prex == null) {
			return s.concat(tmp);
		}
		return prex.concat(s).concat(tmp);
	}

	/**
	 * 前缀为E的36进制uuid
	 * 
	 * @return
	 */
	public static String uuidOf36StringE() {
		return uuidOf36String("E", 14);
	}

	public static String uuidOf36String(String classes) {
		return uuidOf36String(classes, 14);
	}

	private static class LazyHolder {
		private static final KSequenceGenerator INSTANCE = new KSequenceGenerator();
	}

}